package net.uofitorn;

import java.net.ServerSocket;

public class AsteroidRunnerServerMain {
	
	private static final int MAX_SIMULTANEOUS_CLIENTS = 40;
	private static final int PLAYER_ONE = 1;
	private static final int PLAYER_TWO = 2;
	private static AsteroidRunnerServerThread[] servers;
	
	public static void main( String[] args )
	{
    	System.out.println("The server has started");
    	AsteroidRunnerServerMain serverMain = new AsteroidRunnerServerMain();
    	int clientConnected = 0;
    	boolean playerTwoWaitingToJoin = false;
    	ServerSocket listener = null;
    	servers = new AsteroidRunnerServerThread[MAX_SIMULTANEOUS_CLIENTS];
    	
    	try {
    		listener = new ServerSocket(3000);
    		while (true) {
    			if (playerTwoWaitingToJoin == false) {
    				servers[clientConnected] = new AsteroidRunnerServerThread(listener.accept(), serverMain, 1, clientConnected);
    				Thread t = new Thread(servers[clientConnected]);
    				t.start();
    				System.out.println("Player one connected.  clientConnected: " + clientConnected);
    				servers[clientConnected].sendPlayerNumber(PLAYER_ONE);
    				clientConnected++;
    				playerTwoWaitingToJoin = true;
    			}
    			else {
    				servers[clientConnected] = new AsteroidRunnerServerThread(listener.accept(), serverMain, 2, clientConnected);
    				Thread t = new Thread(servers[clientConnected]);
    				t.start();
    				System.out.println("Player two connected.  clientConnected: " + clientConnected);
    				servers[clientConnected].sendPlayerNumber(PLAYER_TWO);
    				servers[clientConnected - 1].sendPlayerNumber(PLAYER_TWO);
    				Thread.sleep(1000);
    				servers[clientConnected - 1].sendStartMessage(servers[clientConnected]);
    				servers[clientConnected].sendStartMessage(servers[clientConnected - 1]);	
    				playerTwoWaitingToJoin = false;
    				clientConnected++;
    				if (clientConnected == MAX_SIMULTANEOUS_CLIENTS - 1) {
    					clientConnected = 0;
    				}
    			}  			
    		}
    	} catch (Exception e) {
    		System.out.println("Encountered exception: " + e.toString());
    	} finally {
    		try {
    			listener.close();
    		} catch (Exception e) {
    			System.out.println("Exception closing socket: " + e.toString());
    		}
    	}
    }  
	
	public void endThread(int connectedID) {
		System.out.println("In ServerMain, stopping thread: " + connectedID);
		//servers[connectedID].stop();
	}
	
}
